package com.augmentum.oes.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.augmentum.oes.common.AppContext;

public class SessionUtil {

    private static Object getSessionInThread() {
        Object session = AppContext.getInstance().getData("HTTP_SESSION");
        return session;
    }

    public static void addSession(String key, Object obj) {
        Object session = getSessionInThread();
        if (session == null) {
            return;
        }
        try {
            Class<?>[] claz = {String.class, Object.class};
            Method method = session.getClass().getMethod("setAttribute", claz);
            Object[] param = {key, obj};
            method.invoke(session, param);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static void removeSession(String key) {
        Object session = getSessionInThread();
        if (session == null) {
            return;
        }
        try {
            Class<?>[] claz = {String.class};
            Method method = session.getClass().getMethod("removeAttribute", claz);
            Object[] param = {key};
            method.invoke(session, param);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static Object getSession(String key) {
        Object session = getSessionInThread();
        if (session == null) {
            return null;
        }
        Object target = null;
        try {
            Class<?>[] claz = {String.class};
            Method method = session.getClass().getMethod("getAttribute", claz);
            Object[] param = {key};
            target = method.invoke(session, param);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return target;
    }
    public static void invalidate() {
        Object session = getSessionInThread();
        if (session == null) {
            return;
        }
        try {
            Method method = session.getClass().getMethod("invalidate");
            method.invoke(session);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
